package com.hctg.forced2sleep.service;

import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.service.wallpaper.WallpaperService;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

import com.actor.myandroidframework.utils.LogUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.hctg.forced2sleep.receiver.WallpaperSettingReceiver;
import com.hctg.forced2sleep.utils.WallpaperUtils;

import java.io.IOException;

/**
 * description: 壁纸设置, 参考: <a href="https://github.com/DingMouRen/VideoWallpaper">VideoWallpaper</a>
 *
 * @author : ldf
 * @date : 2024/5/4 on 18:29
 */
public class MyWallpaperService extends WallpaperService {

    private Engine engine;
    private WallpaperSettingReceiver settingReceiver;

    @Override
    public Engine onCreateEngine() {
        LogUtils.error("2.MyWallpaperService: onCreateEngine");
        if (WallpaperUtils.getIsVideoWallpaper()) {
            engine = new VideoWallpaperEngine();
        } else {
            engine = new PictureWallpaperEngine();
        }
        return engine;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.error("1.MyWallpaperService: onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.error("MyWallpaperService: onDestroy");
    }

    private class PictureWallpaperEngine extends WallpaperService.Engine {

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            //设置可触摸
            setTouchEventsEnabled(true);
            super.onCreate(surfaceHolder);
            LogUtils.error("3.PictureWallpaperEngine: onCreate");
            settingReceiver = new WallpaperSettingReceiver();
//            registerReceiver(settingReceiver, );
        }

        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
            LogUtils.error("4.PictureWallpaperEngine: onSurfaceCreated");
            String picturePath = WallpaperUtils.getVideoPath();
            LogUtils.errorFormat("PictureWallpaperEngine.picturePath: %s", picturePath);
            Bitmap bitmap = null;
            if (TextUtils.isEmpty(picturePath)) {
                Drawable drawable = WallpaperUtils.getWallpaperDesktop(MyWallpaperService.this);
                if (drawable instanceof BitmapDrawable) {
                    bitmap = ((BitmapDrawable) drawable).getBitmap();
                }
            } else {
                bitmap = ImageUtils.getBitmap(picturePath);
            }

            if (bitmap == null) return;

            Canvas lockCanvas = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try {
                    lockCanvas = holder.lockHardwareCanvas();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                lockCanvas = holder.lockCanvas();
            }
            if (lockCanvas == null) {
                lockCanvas = holder.lockCanvas();
            }
            try {
                if (lockCanvas != null) {
                    lockCanvas.save();
//                    lockCanvas.drawBitmap(bitmap, (Rect) null, new RectF(f2, f5, f4, f6), (Paint) null);
                    lockCanvas.drawBitmap(bitmap, 0, 0, (Paint) null);
                    lockCanvas.restore();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lockCanvas != null) {
                    try {
                        holder.unlockCanvasAndPost(lockCanvas);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //surface发生改变时调用，测试遇到如：preview，setwallpaper，以及横竖屏切换
        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            LogUtils.error("5.PictureWallpaperEngine: onSurfaceChanged");
        }

        //壁纸可视与否发生变化时
        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            //打开app后, 桌面visible=false. 返回桌面后visible=true
            LogUtils.errorFormat("6.PictureWallpaperEngine: onVisibilityChanged: visible=%b", visible);
        }

        /**
         * 壁纸当前显示页相当于原点坐标发生位移的时候，当然只要onSurfaceChanged发生，则onOffsetsChanged 也一定会被调用。<br />
         * 设置 {@link WallpaperManager#setWallpaperOffsetSteps(float, float)}
         * 设置 {@link WallpaperManager#setWallpaperOffsets(IBinder, float, float)} 的时候, 会回调这个方法
         * @param xOffset
         * @param yOffset
         * @param xOffsetStep
         * @param yOffsetStep
         * @param xPixelOffset
         * @param yPixelOffset
         */
        //setTouchEventsEnabled(false)时:
        //xOffset=0,        yOffset=0,        xOffsetStep=0.5,      yOffsetStep=-1,       xPixelOffset=0, yPixelOffset=0
        //setTouchEventsEnabled(true) 时:
        //xOffset=0.333333, yOffset=0.500000, xOffsetStep=0.333333, yOffsetStep=1.000000, xPixelOffset=0, yPixelOffset=0
        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            LogUtils.errorFormat("7.PictureWallpaperEngine: onOffsetsChanged: xOffset=%f, yOffset=%f, xOffsetStep=%f, yOffsetStep=%f, xPixelOffset=%d, yPixelOffset=%d",
                    xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
        }

        @Override
        public void onTouchEvent(MotionEvent event) {
            super.onTouchEvent(event);
//            LogUtils.errorFormat("onTouchEvent, action=%d", event.getAction());
//            LogUtils.errorFormat("x=%f, y=%f", event.getX(), event.getY());
//            LogUtils.errorFormat("RawX=%f, RawY=%f", event.getRawX(), event.getRawY());
//            WallpaperManager wallpaperManager = WallpaperManager.getInstance(MyWallpaperService.this);
//            wallpaperManager.setWallpaperOffsets(MyWallpaperService.this.tok);
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            //点击"应用"后
            LogUtils.error("8.PictureWallpaperEngine: onSurfaceDestroyed");
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            LogUtils.error("9.PictureWallpaperEngine: onDestroy");
        }

        @Override
        public boolean isPreview() {
            return super.isPreview();
        }
    }


    private class VideoWallpaperEngine extends WallpaperService.Engine {

        private MediaPlayer mMediaPlayer;

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            LogUtils.error("3.VideoWallpaperEngine: onCreate");
            settingReceiver = new WallpaperSettingReceiver();
//            registerReceiver(settingReceiver, );
        }

        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
            LogUtils.error("4.VideoWallpaperEngine: onSurfaceCreated");
            String videoPath = WallpaperUtils.getVideoPath();
            LogUtils.errorFormat("VideoWallpaperEngine.videoPath: %s", videoPath);
            if (TextUtils.isEmpty(videoPath)) return;

            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setSurface(holder.getSurface());
            try {
                mMediaPlayer.setDataSource(videoPath);
                mMediaPlayer.setLooping(true);
                mMediaPlayer.setVolume(0f, 0f);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            LogUtils.error("5.VideoWallpaperEngine: onSurfaceChanged");
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            //打开app后, 桌面visible=false. 返回桌面后visible=true
            LogUtils.errorFormat("6.VideoWallpaperEngine: onVisibilityChanged: visible=%b", visible);
            if (mMediaPlayer == null) return;
            if (visible) {
                mMediaPlayer.start();
            } else {
                mMediaPlayer.pause();
            }
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            LogUtils.errorFormat("7.VideoWallpaperEngine: onOffsetsChanged: xOffset=%f, yOffset=%f, xOffsetStep=%f, yOffsetStep=%f, xPixelOffset=%d, yPixelOffset=%d",
                    xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            //点击"应用"后
            LogUtils.error("8.VideoWallpaperEngine: onSurfaceDestroyed");
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            LogUtils.error("9.VideoWallpaperEngine: onDestroy");
        }

        @Override
        public boolean isPreview() {
            return super.isPreview();
        }
    }
}